<?php

namespace App\Console\Commands;

use App\Models\CheckOrderRecord;
use App\Models\Setting as SettingModel;
use App\Service\WxArticleData;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CheckOrderStat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check_order:stat {date?} {hour?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检测订单数据统计';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $date = $this->argument('date') ?: Carbon::now()->toDateString();
        if ($this->argument('hour') === null) {
            $hour = Carbon::now()->hour;//没传入参数，取当前小时
        } elseif ($this->argument('hour') === 0) {
            $hour = 0;
        } else {
            $hour = $this->argument('hour');
        }
        //检查PV数
        $check_pv_num = json_decode(SettingModel::query()->firstOrCreate(['key' => 'check_pv_num'], ['value' => null])->value);
        $redis = Redis::connection();
        try {
            CheckOrderRecord::query()->groupBy('check_order_id')->where([
                'date' => $date,
                'hour' => $hour
            ])->selectRaw('count(*) as pv,check_order_id')->get()->each(function ($item) use ($date, $hour, $check_pv_num, $redis) {

                //获取检测订单阅读数
                $read_data = WxArticleData::get(($item->checkOrder->url));
                $read_num_incr = 0;

                if ($read_data->code == 200) {

                    $read_num_incr = $read_data->read_num - $item->checkOrder->initialization_read_num;
                    $item->checkOrder->initialization_read_num = $read_data->read_num;
                    $item->checkOrder->save();
                } else {
                    throw new \Exception($read_data->msg);
                }
                $check_order_stat = \App\Models\CheckOrderStat::query()->firstOrCreate([
                    'date' => $date,
                    'hour' => $hour,
                    'check_order_id' => $item->check_order_id,
                    'flow_channel_id' => $item->checkOrder->flow_channel_id]);

                $check_order_stat->increment('read_num_incr',$read_num_incr);
                $check_order_stat->pv =  $item->pv;
                $check_order_stat->save();

                if ($item->pv > $check_pv_num) {
                    //检测PV超限，停止导入
                    $redis->del('check_order_' . $item->checkOrder->flowChannel->param);
                    $item->checkOrder->flow_channel_id = null;
                    $item->checkOrder->save();
                }
            });

        } catch (\Exception $exception) {
            Log::error('检测订单统计错误：' . $exception->getMessage());
        }

    }
}
